/*
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * $Id: PairMatchingAnalyzer.java 401 2007-02-10 11:23:44Z jack.rybicki $
 */
package logmatcher.analyzers;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import logmatcher.Configurable;
import logmatcher.InitializationException;
import logmatcher.LogEventProducer;
import logmatcher.LogEventListener;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.spi.LoggingEvent;


/**
 *  Class performs pairing of messages. Each pair is identified by some qualifier. Each type in the pair is
 *  distinguished by message content.
 *
 *  @version $Revision: 401 $
 */
public class PairMatchingAnalyzer implements Configurable, LogEventListener {
    //~ Static fields/initializers -------------------------------------------------------------------------------------

    /** Class logger. */
    private static final Log LOGGER = LogFactory.getLog(PairMatchingAnalyzer.class);

    //~ Instance fields ------------------------------------------------------------------------------------------------

    /** Pattern used to extract pair identifier. */
    private Pattern idPattern;

    /** First pair element finder. */
    private Pattern pairElement1Pattern;

    /** Second pair element finder. */
    private Pattern pairElement2Pattern;

    /** Determines if to log messages containing id, but not matching any of pair element patterns.x */
    private boolean showInvalidMessages;

    /** Contains only unmatched pairs */
    private Map<String, PairState> unmatchedPairs = new HashMap<String, PairState>();

    //~ Constructors ---------------------------------------------------------------------------------------------------

/**
     * Creates a new PairMatchingAnalyzer object.
     */
    public PairMatchingAnalyzer() {
        super();
    }

    //~ Methods --------------------------------------------------------------------------------------------------------

    /**
     *  Process received message.
     *
     *  @param message incoming object.
     */
    public void receiveLogEvent(Object message) {
        if (message instanceof LoggingEvent) {
            LoggingEvent event = (LoggingEvent)message;
            String m = String.valueOf(event.getMessage());
            Matcher matcher = idPattern.matcher(m);

            if (matcher.find()) {
                // extract message id
                String id = matcher.group();
                boolean newPair = false;
                PairState p = unmatchedPairs.get(id);

                if (p == null) {
                    p = new PairState(false, false);
                    newPair = true;
                }

                // check if message contains first pattern
                matcher = pairElement1Pattern.matcher(m);

                if (matcher.find()) {
                    p.element1Found = true;
                }

                // check if message contains second pattern
                matcher = pairElement2Pattern.matcher(m);

                if (matcher.find()) {
                    p.element2Found = true;
                }

                if (newPair) {
                    // if new pair is unmatched, put it into the map
                    if (p.element1Found ^ p.element2Found) {
                        unmatchedPairs.put(id, p);
                    }
                } else {
                    // if pair matched, remove it from the map
                    if (p.element1Found && p.element2Found) {
                        unmatchedPairs.remove(id);
                    }
                }

                printReport();
            } else {
                if (showInvalidMessages) {
                    LOGGER.warn("Skipped message: " + m);
                }
            }
        }
    }


    /**
     *  @todo DOCUMENT ME!
     *
     *  @return TODO: DOCUMENT ME!
     */
/**
     * Return unmatched ids. Used for test purposes.
     *
     * @return unpaired ids. 
     */
    Set<String> getUnmatchedIds() {
        return unmatchedPairs.keySet();
    }


    /**
     *  Read the object properties from configuration source.
     *
     *  @see logmatcher.Configurable#configure(org.apache.commons.configuration.Configuration, java.lang.String)
     */
    public void configure(Configuration config, String id)
        throws InitializationException {
        Object ob = config.getProperty("logmatcher.logbuffer");

        if (ob instanceof LogEventProducer) {
            LogEventProducer logEventProducer = (LogEventProducer)ob;
            logEventProducer.addLogEventListener(this);
        } else {
            throw new InitializationException("Not initialized log buffer at " + "logmatcher.logbuffer");
        }

        String s = config.getString(id + ".id");

        if (s == null) {
            throw new InitializationException("Missing configuration value: " + id + ".id");
        }

        idPattern = Pattern.compile(s);

        s = config.getString(id + ".pairelement1");

        if (s == null) {
            throw new InitializationException("Missing configuration value: " + id + ".pairelement1");
        }

        pairElement1Pattern = Pattern.compile(s);

        s = config.getString(id + ".pairelement2");

        if (s == null) {
            throw new InitializationException("Missing configuration value: " + id + ".pairelement2");
        }

        pairElement2Pattern = Pattern.compile(s);

        showInvalidMessages = config.getBoolean(id + ".showinvalidmessages");
    }


    /**
     *  DOCUMENT ME!
     */
    public void printReport() {
        LOGGER.info("Number of unmatched elements: " + this.unmatchedPairs.size());

        Set<String> keys = unmatchedPairs.keySet();
        StringBuilder sb = new StringBuilder((keys.size() * 4) + 10);
        sb.append("Unmatched ids: ");

        for (String s : keys) {
            sb.append(s);
            sb.append(",");
        }

        LOGGER.info(sb.toString());
    }

    //~ Inner Classes --------------------------------------------------------------------------------------------------

    /**
     *  Describes a pair state.
     */
    private static final class PairState {
        //~ Instance fields --------------------------------------------------------------------------------------------

        /** <code>true</code> if first element of the pair has been found. */
        public boolean element1Found;

        /** <code>true</code> if second element of the pair has been found. */
        public boolean element2Found;

        //~ Constructors -----------------------------------------------------------------------------------------------

/**
         * Creates a new PairState object.
         *
         * @param el1 state of first element of the pair.
         * @param el2 state of second element of the pair.
         */
        public PairState(boolean el1, boolean el2) {
            this.element1Found = el1;
            this.element2Found = el2;
        }
    }
}
